package com.ww.dynamic.spel;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.Date;

public class MethodExprSample {

    public static void main(String[] args) {
        User user = new User();
        SpelExpressionParser parser = new SpelExpressionParser();
        StandardEvaluationContext context = new StandardEvaluationContext(user);

        // 调用String方法
        String subString = parser.parseExpression("'Spring SpEL'.substring(7)").getValue(String.class);
        Integer index = parser.parseExpression("'Spring SpEL'.indexOf('SpEL')").getValue(Integer.class);

        // 调用实例方法
        boolean isCorrect = parser.parseExpression("validatePassword('123456')").getValue(context, Boolean.class);
    }

    @ToString
    @Data
    static class User {

        private String userName;

        private Date lastVisit;

        private Integer credits;

        private PropertyExprSample.PlaceOfBirth placeOfBirth;
    }

    @ToString
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    static class PlaceOfBirth {

        private String province;

        private String city;
    }
}
